#include "myutils.h"
#include <BAUTILS.H>
#include <eikenv.h>

/*
 * class dbutil
 */

#define KDBUtilUid TUid::Uid(0x080F046D)

DBUtil* DBUtil::Static()
{
	DBUtil* instance = static_cast<DBUtil*> ( CCoeEnv::Static( KDBUtilUid ) );

	if ( !instance )
	{
		instance = new ( ELeave ) DBUtil;
		instance->ConstructL();
	}

  	return instance;
}

DBUtil::DBUtil() : CCoeStatic(KDBUtilUid, -1)
{
}

void DBUtil::ConstructL()
{
}

DBUtil::~DBUtil()
{
}

//确保dest有256个字节长度
void DBUtil::ConvertDesToStr(const TPtrC& source, char* dest)
{
	dest[source.Length()] = 0;		
	for(int i = 0; i < source.Length(); i++)
	dest[i] = source[i];	
}

int DBUtil::FindByStr(c4_View* view, char* fieldname, char* keyvalue)
{
	int pos = -1;
	c4_StringProp strfield(fieldname);
	pos = view->Find(strfield[keyvalue]);

	return pos;
}

TPtrC8 DBUtil::FieldStr8Value(c4_View* view, char* fieldname, int pos)
{
	c4_StringProp strfield(fieldname);
	iStrTemp = c4_String(strfield((*view)[pos]));
	return iStrTemp.Ptr8();
}

TPtrC8 DBUtil::FieldUtf8Value(c4_View* view, char* fieldname, int pos)
{
	c4_BytesProp binfield(fieldname);
	c4_Bytes bin;
	bin = binfield(((*view)[pos]));

	const int len = bin.Size();
	if(len == 0) return _L8("");
	
	TPtrC8 ptr8((TUint8*)bin.Contents(), len);
	
	return ptr8;
}

bool DBUtil::FindBookPrefix(const TPtrC& path)
{
	int found = path.Find(_L("book://"));
	return (found == 0);
}

TPtrC DBUtil::GetRealPath(const TPtrC& path)
{
	int found = path.Find(_L("book://"));
	TPtrC temp = path;	
	if(found == 0)
		return path.Right(path.Length()-7);

	return temp;
}

//end dbutil

MyImgFile::MyImgFile()
{
	iAllocated = false;
	TBuf8<10> buf;

}

MyImgFile::~MyImgFile()
{	
_rfile.Close();
_fs.Close();	
delete iFileData8;
iFileData8 = NULL;	

}

void MyImgFile::SaveToFile(const TDesC8& data)
{
	int pos = 0;
	_rfile.Seek(ESeekEnd, pos);
	_rfile.Write(data);
}


const TPtrC8 MyImgFile::ImgBlock(int pos, int size)
{
if(iAllocated == true)
	User::Panic(_L("img error"), 0);

	iFileData8 = HBufC8::NewL(size);

	TPtr8 ptr = iFileData8->Des();
	_rfile.Read(pos, ptr, size);

	iAllocated = true;
	
	return ptr;
}


int MyImgFile::Length()
{
	int size;
	_rfile.Size(size);

	return size;
}

void MyImgFile::Init(const TDesC& FileName)
{
User::LeaveIfError(_fs.Connect());
	TBool exist = BaflUtils::FileExists(_fs, FileName);
	
	
	if(exist)
	{
		TInt aFileMode = EFileRead|EFileWrite|EFileShareAny;
		User::LeaveIfError(_rfile.Open(_fs, FileName, aFileMode));
	}
	else
	{
		TInt aFileMode = EFileRead|EFileWrite|EFileShareAny;
		
		User::LeaveIfError(_rfile.Replace(_fs, FileName, aFileMode));
	}
}


void MyImgFile::ReleaseBlock()
{
if(iAllocated == false)
	User::Panic(_L("img error"), 1);	
delete iFileData8;
iFileData8 = NULL;
iAllocated = false;
	
}
